<template>
    <view>
        <view class='mask' v-if='isShowAuth && code' @click='close'></view>
        <view class="Popup" v-if='isShowAuth && code'>
            <view class="popupLogin-content">
                <view class="popup_header">
                    <view class="popup_avatar">
                        <text>选择头像</text>
                        <button class="chooseAvatar" open-type="chooseAvatar" @chooseavatar="chooseavatar">
                            <image class="popup_img"
                                :src="loginForm.avatarUrl || 'https://weapp.miyingbl.com/mini_babybaby/my/avatar.png'" />
                        </button>
                    </view>
                    <view class="popup_nickname">
                        <text>填写昵称</text>
                        <input type="nickname" @change="inputChange" v-model="loginForm.nickname" placeholder="请填写昵称"
                            class="popup_input" />
                    </view>
                </view>

                <view class="popup_con">
                    <text>说明</text>
                    <text>1、点击头像选择框可选择“用微信头像”;</text>
                    <text>2、点击昵称输入框后可选择“用微信昵称”;</text>
                    <text>3、平台不会将您的信息泄露给第三方平台;</text>
                </view>

                <view class="popup_check">
                    <checkbox-group @change="isChecked = !isChecked">
                        <label>
                            <checkbox :checked="false" size="mini" color="#4a4a4a" style="transform: scale(0.8);" />
                        </label>
                    </checkbox-group>
                    <view class="popup_check_text">
                        <text>我已阅读并同意</text>
                        <text @click.stop="setTime('agreementPopup', 'sys_user_agree')"
                            class="popup_check_text_c">《用户协议》</text>
                        <i style="font-size: 24rpx;">及</i>
                        <text @click.stop="setTime('agreementPopup', 'sys_userr_privacy')"
                            class="popup_check_text_c">《隐私政策》</text>
                    </view>
                </view>

                <view class="popup_btn">
                    <view class="cancel" @click="close">取消</view>
                    <view>
                        <button class="item grant" hover-class="none" @tap="getUserProfile"><text
                                class="text">去登录</text></button>
                    </view>

                </view>
            </view>
            <uni-popup ref="agreementPopup" background-color="tranparent">
                <view class="agreementPopup-content">
                    <view class="agreementPopup-content-title">
                        {{ agreementInfo.title }}
                        <u-icon name="close" color="#868686" size="24" @click="close('agreementPopup')"></u-icon>
                    </view>
                    <scroll-view class="agreementPopup-content-bodyer" :scroll-y="true">
                        <view v-html="agreementInfo[agreement]" class="agreementPopup-content-bodyer-text"> </view>

                    </scroll-view>
                    <view class="agreementPopup-content-footer-btn" v-if="isShowInterval" @click="closeInterval">
                        {{ time }}秒后关闭
                    </view>

                </view>
            </uni-popup>

        </view>
    </view>
</template>
<script>
// +----------------------------------------------------------------------
// | CRMEB [ CRMEB赋能开发者，助力企业发展 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2016~2021 https://www.crmeb.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed CRMEB并不是自由软件，未经许可不能去掉CRMEB相关版权
// +----------------------------------------------------------------------
// | Author: CRMEB Team <admin@crmeb.com>
// +----------------------------------------------------------------------

import Cache from '../utils/cache';

import {
    getMenuList,
    getUserInfo,
    setVisit,
    getAgreementApi,
    uploadApi
} from '@/api/user.js';
import {
    getLogo,
    commonAuth
} from '../api/public';
import {
    LOGO_URL,
    USER_INFO,
    EXPIRES_TIME
} from '../config/cache';
import {
    mapGetters
} from 'vuex';
import Routine from '../libs/routine';
import {
    configMap
} from '@/utils/index';
import Auth from '../libs/wechat';
import {
    toLogin
} from '../libs/login';
// #ifdef MP
import editUserModal from '@/components/eidtUserModal/index.vue'
// #endif
export default {
    name: 'Authorize',
    props: {
        isAuto: {
            type: Boolean,
            default: true
        },
        isGoIndex: {
            type: Boolean,
            default: true
        },
        isShowAuth: {
            type: Boolean,
            default: false
        }
    },
    components: {
        // #ifdef MP
        editUserModal
        // #endif
    },
    data() {
        return {
            title: '用户登录',
            info: '请先登录，将为您提供更好的服务！',
            //#ifdef H5
            isWeixin: this.$wechat.isWeixin(),
            //#endif
            //#ifdef MP
            title: '授权提醒',
            info: '请授权头像等信息，以便为您提供更好的服务！',
            //#endif
            canUseGetUserProfile: false,
            code: null,
            top: 0,
            mp_is_new: this.$Cache.get('MP_VERSION_ISNEW') || false,
            editModal: false, // 编辑头像信息
            loginForm: {
                avatarUrl: ''
            },
            isChecked: false,
            time: 0,
            timerId: null,
            isShowInterval: true,
            agreementInfo: {},
            agreement: ''
        }
    },
    computed: {
        ...mapGetters(['isLogin', 'userInfo', 'viewColor']),
        ...configMap(['routine_logo'])
    },
    watch: {
        isLogin(n) {
            n === true && this.$emit('onLoadFun', this.userInfo);
        },
        isShowAuth(n) {
            this.getCode(this.isShowAuth)
        }
    },
    created() {
        this.top = uni.getSystemInfoSync().windowHeight / 2 - 70
        if (wx.getUserProfile) {
            this.canUseGetUserProfile = true
        }
        this.setAuthStatus();
        this.getCode(this.isShowAuth)
    },
    methods: {
        closeInterval() {
            this.$refs.agreementPopup.close()
            this.time = 60
            clearInterval(this.timerId)
        },
        async getAgreement(type) {
            try {
                const res = await getAgreementApi(type)
                this.agreementInfo = res.data
            } catch (error) {

            }
        },
        open(key) {
            this.$refs[key].open('center')
        },
        setTime(key, id) {
            this.agreement = id
            this.getAgreement(id)
            this.open(key)
            this.time = 60
            clearInterval(this.timerId)
            this.timerId = null
            this.timerId = setInterval(() => {
                this.time--
                if (this.time <= 0) {
                    clearInterval(this.timerId)
                    this.$refs.agreementPopup.close()
                }
            }, 1000)
        },
        // #ifdef MP
        editSuccess() {
            this.editModal = false
            this.$emit('onLoadFun', this.userInfo);
        },
        closeEdit() {
            this.editModal = false
        },
        // #endif
        setAuthStatus() {
            //#ifdef MP
            Routine.authorize().then(res => {
                if (res.islogin === false)
                    this.$emit('onLoadFun', this.userInfo);
            }).catch(res => {
                if (this.isAuto)
                    this.$emit('authColse', true);
            })
            //#endif
        },
        getCode(n) {
            // #ifdef MP
            if (n) {
                uni.showLoading({
                    title: '正在登录中'
                });
                Routine.getCode().then(code => {
                    uni.hideLoading();
                    this.code = code;
                }).catch(e => {
                    uni.hideLoading();
                    uni.showToast({
                        title: '登录失败',
                        duration: 2000
                    });
                })
            } else {
                this.code = null;
            }
            // #endif
            // #ifndef MP
            if (n) {
                this.code = 1;
            }
            // #endif
        },
        toWecahtAuth() {
            toLogin(true);
        },
        getUserProfile() {
            let self = this;
            Routine.getUserProfile()
                .then(res => {
                    const app = getApp();
                    let userInfo = res.userInfo;
                    let rawData = JSON.parse(res.userInfo.rawData)
                    console.log(rawData)
                    rawData.avatarUrl = this.loginForm.avatarUrl
                    rawData.nickName = this.loginForm.nickname
                    userInfo.code = this.code;
                    userInfo.spread = app.globalData.spid; //获取推广人ID
                    userInfo.spread_code = app.globalData.code; //获取推广人分享二维码ID
                    userInfo.userInfo = this.loginForm
                    userInfo.rawData = JSON.stringify(rawData)
                    console.log(userInfo)
                    commonAuth({
                        auth: {
                            type: 'routine',
                            auth: userInfo
                        }
                    }).then(res => {
                        if (res.data.status == 200) {
                            let time = res.data.result.expires_time - Cache.time();
                            self.$store.commit('UPDATE_USERINFO', res.data.result.user);
                            self.$store.commit('LOGIN', {
                                token: res.data.result.token,
                                time: time
                            });
                            self.$store.commit('SETUID', res.data.result.user.uid);
                            Cache.set(EXPIRES_TIME, res.data.result.expires_time, time);
                            Cache.set(USER_INFO, res.data.result.user, time);
                            this.$emit('onLoadFun', res.data.result.user);
                            if (res.data.result.user.isNew && this.mp_is_new) {
                                this.editModal = true;
                            }
                            this.close()
                        } else {
                            uni.setStorageSync('auth_token', res.data.result.key);
                            return uni.navigateTo({
                                url: '/pages/users/login/index'
                            })
                        }
                    }).catch(res => {
                        uni.hideLoading();
                        uni.showToast({
                            title: res.message,
                            icon: 'none',
                            duration: 2000,

                        });
                    });
                })
                .catch(res => {
                    uni.hideLoading();
                });
        },
        close() {
            console.log(1312)
            let pages = getCurrentPages(),
                currPage = pages[pages.length - 1];
            this.$emit('authColse', false);
            // if (this.isGoIndex) {
            // 	uni.switchTab({
            // 		url: '/pages/index/index'
            // 	});
            // } else {
            // 	this.$emit('authColse', false);
            // }
        },
        // 上传头像
        chooseavatar(e) {
            let that = this;
            const {
                avatarUrl
            } = e.detail
            this.$util.uploadImgs('upload/image', avatarUrl, (res) => {
                this.loginForm.avatarUrl = res.data.path
            }, (err) => {
                console.log(err)
            })
        },
        // 用户名称
        inputChange(e) {
            this.loginForm.nickname = e.detail.value
        },
        wxLogin() {
            const app = getApp();
            let userInfo = res.userInfo;
            userInfo.code = this.code;
            userInfo.spread = app.globalData.spid; //获取推广人ID
            userInfo.spread_code = app.globalData.code; //获取推广人分享二维码ID

        }
    },

}
</script>

<style scoped lang='scss'>
.Popup {
    position: fixed;
    top: 0;
    left: 0;
    z-index: 1000;
    bottom: 0;
    right: 0;
}

.Popup {
    .logo-auth {
        z-index: -1;
        position: absolute;
        left: 50%;
        top: 0%;
        transform: translate(-50%, -50%);
        width: 150rpx;
        height: 150rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        border: 8rpx solid #fff;
        border-radius: 50%;
        background: #fff;
    }

    .image {
        height: 42rpx;
        margin-top: -54rpx;
    }
}

.Popup .title {
    font-size: 28rpx;
    color: #000;
    text-align: center;
    margin-top: 30rpx;
    align-items: center;
    justify-content: center;
    width: 500rpx;
    display: flex;
}

.Popup .tip {
    font-size: 22rpx;
    color: #555;
    padding: 0 24rpx;
    margin-top: 25rpx;
    display: flex;
    align-items: center;
    justify-content: center;
}

.Popup .bottom .item {
    width: 250rpx;
    height: 80rpx;
    background-color: #eeeeee;
    text-align: center;
    line-height: 80rpx;
    margin-top: 54rpx;
    font-size: 24rpx;
    color: #666;

    .text {
        font-size: 24rpx;
        color: #666;
    }
}

.Popup .bottom .item.on {
    width: 500rpx;
}

.flex {
    display: flex;
    flex-direction: row;
}

.Popup .bottom .item.grant {
    font-weight: bold;
    background-color: #E93323;
    /* background-color: var(--view-theme); */
    border-radius: 0;
    padding: 0;

    .text {
        font-size: 28rpx;
        color: #fff;
    }
}

.mask {
    position: fixed;
    top: 0;
    right: 0;
    left: 0;
    bottom: 0;
    background-color: rgba(0, 0, 0, 0.65);
    z-index: 99;
}

.popupLogin-content {
    position: absolute;
    bottom: 0;
    width: 750rpx;
    padding-bottom: 30rpx;
    background-color: #fff;
    border-radius: 16rpx 16rpx 0 0;

    .popup_header {
        padding: 100rpx 50rpx 0 50rpx;

        .popup_avatar {
            display: flex;
            justify-content: space-between;
            align-items: center;

            ::v-deep .u-upload__wrap__preview__image {
                width: 96rpx !important;
                height: 96rpx !important;
                border-radius: 50%;
            }

            .popup_img {
                width: 110rpx;
                height: 110rpx;
                border-radius: 50%;
                background-color: #fff;
                border: 2rpx solid #ccc;
            }
        }

        .popup_nickname {
            display: flex;
            justify-content: space-between;
            align-items: center;
            border-bottom: 1rpx solid #ccc;
            margin-top: 50rpx;
            padding-bottom: 35rpx;

            .popup_input {
                font-size: 24rpx;
                text-align: right;
            }
        }

        // .phone-number {}
    }

    .popup_con {
        display: flex;
        flex-direction: column;
        font-size: 24rpx;
        color: #4a4a4a;
        margin: 20rpx 50rpx;
    }

    .popup_check {
        display: flex;
        align-items: center;
        margin: 0 45rpx;
        line-height: 1;

        .popup_check_text {
            display: flex;
            font-size: 24rpx;

            .popup_check_text_c {
                color: #767474;
            }
        }
    }

    .popup_btn {
        display: flex;
        justify-content: space-between;
        margin: 40rpx 50rpx 0 50rpx;

        .cancel {
            font-size: 24rpx;
            color: #fff;
            background-color: #ccc;
            padding: 15rpx 60rpx;
            border-radius: 30rpx;
        }

        .sure {
            font-size: 24rpx;
            color: #fff;
            border-radius: 30rpx;
            background: var(--view-theme);
            padding: 15rpx 190rpx;

        }

        .grant {
            font-size: 24rpx;
            color: #fff;
            border-radius: 30rpx;
            background: #E93323;
            padding: 15rpx 190rpx;

            .text {
                font-size: 28rpx;
                color: #fff;
            }
        }
    }
}</style>